package com.droowa.controller;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.droowa.domain.BusinessRecord;
import com.droowa.domain.CompletePC;
import com.droowa.domain.CompletePCResult;
import com.droowa.domain.Customer;
import com.droowa.domain.OrderInfo;
import com.droowa.domain.CustomerOut;
import com.droowa.domain.OrderList;
import com.droowa.domain.OrderProduct;
import com.droowa.domain.ShopManager;
import com.droowa.exception.DuplicatedIdException;
import com.droowa.model.service.BusinessRecordService;
import com.droowa.model.service.CustomerService;
import com.droowa.model.service.MileageOptionService;
import com.droowa.model.service.OrderService;
import com.droowa.model.service.DeliveryEnterpriseManagementService;
import com.droowa.model.service.ProductManagementService;
import com.droowa.model.service.ShopManagerService;
import com.droowa.util.SimpleRegistrationNotifier;

@Controller
@RequestMapping("/customer/")
public class CustomerController {
	
	@Autowired
	private CustomerService service;
	@Autowired
	private ShopManagerService smService;
	@Autowired
	private SimpleRegistrationNotifier SRN;
	@Autowired
	private BusinessRecordService bRService;
	@Autowired
	private ProductManagementService pmService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private DeliveryEnterpriseManagementService dEMService;

//############################# CheckId ####################################################
	/*
	 * 					회원 가입시에 ID text란에 아이디 체크 ajax처리하기위한 메소드
	 */
	@RequestMapping("checkId.do")		
	public String checkId(String custId, ModelMap map) throws SQLException, DuplicatedIdException{
		Customer customer=service.getCustomerById(custId);
		map.addAttribute("customer", customer);
		return "jsonView";
	}
//############################## LOG - IN ##################################################
	/*
	 * 					GET - 로그인 화면으로 이동
	 * 					POST - 사용자가 ID, Password를 입력하고 "로그인"버튼을 눌렀을때 컨트롤러 이동
	 */
	@RequestMapping(value="login.do", method=RequestMethod.GET)
	public String loginForm(HttpServletRequest request){ // 로그인 창으로 간다.
		request.setAttribute("menu_category", "customer");
		return "customer.login_form";	
	}
	
	@RequestMapping(value="login.do", method=RequestMethod.POST)
	public String login(String custId, String password, HttpSession session, HttpServletRequest request, ModelMap map) throws Exception{
		Customer customer=service.getCustomerById(custId); 
		CustomerOut custOut=service.getCustomerOutById(custId);
		ShopManager manager=smService.getShopManagerByShopManagerId(custId);
		//메인페이지 상품 순위 출력
		List<CompletePCResult> firstList= new ArrayList<CompletePCResult>();
		List<CompletePCResult> secondList= new ArrayList<CompletePCResult>();
		List<CompletePCResult> resultList= new ArrayList<CompletePCResult>();
		resultList = pmService.getCompletePCByPrice(10, 300000);//매개변수 1 : StartPrice, 2: EndPrice
		for(int idx=0; idx<2; idx++){
			firstList.add((CompletePCResult) resultList.get(idx));
		}resultList = pmService.getCompletePCByPrice(300001, 500000);//매개변수 1 : StartPrice, 2: EndPrice
		for(int idx=0; idx<2; idx++){
			firstList.add((CompletePCResult) resultList.get(idx));
		}request.setAttribute("firstList", firstList);
		resultList = pmService.getCompletePCByPrice(500001, 1000000000);//매개변수 1 : StartPrice, 2: EndPrice
		for(int idx=0; idx<2; idx++){
			secondList.add((CompletePCResult) resultList.get(idx));
		}resultList = pmService.getCompletePCByCPUBrand("cpu", "intel");
		for(int idx=0; idx<1; idx++){
			secondList.add((CompletePCResult) resultList.get(idx));
		}resultList = pmService.getCompletePCByCPUBrand("cpu", "amd");
		for(int idx=0; idx<1; idx++){
			secondList.add((CompletePCResult) resultList.get(idx));
		}request.setAttribute("secondList", secondList);
		
		if(custOut==null){				//  1. 탈퇴한 회원인지 테이블에서 검색한다.
			if(manager!=null){			//  2. 관리자가 로그인한 경우
				if(password.equals(manager.getPwd())){
					session.setAttribute("login_info_manager", manager);
					insertBusinessRecord("관리자", "로그인", manager.getSort()); // 업무기록
					return "customer.main";	
				}else{ 
					map.addAttribute("error_message","비밀번호가 올바르지 않습니다.");
					return "customer.login_form";	// Password 틀린 경우
				}
			}	
			if(customer !=null){		//  3. 회원이 로그인한 경우
				if(password.equals(customer.getPassword())){
					session.setAttribute("login_info", customer);
					insertBusinessRecord("회원", "로그인", customer.getCustId()); //업무기록
					return "customer.main";	
				}else{ 						// Password 틀린 경우
					map.addAttribute("error_message","비밀번호가 올바르지 않습니다.");
					return "customer.login_form";
				}	
			}else{							// id  틀린 경우
				map.addAttribute("error_message","정보가 올바르지 않습니다.");
				return "customer.login_form";
			}
		}else{								// 탈퇴한 회원
			map.addAttribute("error_message","탈퇴한 회원입니다.");
			return "customer.login_form";
		}
}
//############################## LOG - OUT #################################################
	/*
	 * 					로그아웃시에 세션 소멸
	 */
	@RequestMapping("logout.do")
	public String logout(HttpSession session) throws SQLException{
		if(session.getAttribute("login_info_manager")!=null){
			ShopManager sm = (ShopManager)session.getAttribute("login_info_manager");
			insertBusinessRecord("관리자", "로그아웃", sm.getSort());			//업무기록
		}else{
			Customer cus = (Customer)session.getAttribute("login_info");
			insertBusinessRecord("회원", "로그아웃", cus.getCustId());			//업무기록
		}
		session.invalidate();
		return "customer.main";
	}
//############################## 회원가입 ###################################################
	/*
	 * 				GET - 회원가입창으로 이동
	 * 				POST - join_form.jsp 에서 회원가입 폼작성후 이동
	 */
	@RequestMapping(value="join.do", method=RequestMethod.GET)
	public String joinForm(HttpServletRequest request){
		return "customer.join_form";
	}
	
	@RequestMapping(value="join.do", method=RequestMethod.POST)
	public String joinCustomer(Customer customer, HttpServletRequest request, ModelMap map) throws Exception{
		Customer cust=service.getCustomerById(customer.getCustId());
		if(cust==null){		//회원가입한 정보가 있는지없는지 체크
			service.joinCustomer(customer);
			insertBusinessRecord("회원", "회원가입", customer.getCustId());		//업무기록
			return "customer.join_success";
		}else{					// 가입한 정보가 있을때
			map.addAttribute("error_message","이미 가입된 회원입니다.");
			return "customer.join_form";
		}
	}
//############################## 아이디찾기 #################################################
	/*
	 * 				GET - 로그인에서 아이디 찾기를 눌렀을때 팝업을띄운다.
	 * 				POST - 전체조회해서 받은 값들로 조회하여 팝업창으로 전달.
	 */
	@RequestMapping(value="searchId.do", method=RequestMethod.GET)
	public String searchId(){
		return "/body/customer/searchId_form.jsp";
	}
	
	@RequestMapping(value="searchId.do", method=RequestMethod.POST)
	public String searchId(Customer customer, HttpServletRequest request) throws SQLException{
		List<Customer> list=service.getCustomerList();
		request.setAttribute("list", list);
		request.setAttribute("customer", customer);
		return "/body/customer/searchId_form.jsp";
	}
//############################## 비밀번호찾기 ###############################################
	/*
	 * 				GET - 로그인에서 비밀번호 찾기를 눌렀을때 팝업을 띄운다.
	 * 				POST - 받은 값을 조회해서 일치하면 이메일로 비밀번호 발송
	 */
	@RequestMapping(value="searchPassword.do", method=RequestMethod.GET)
	public String searchPassword(){
		return "/body/customer/searchPassword_form.jsp";
	}
	
	@RequestMapping(value="searchPassword.do", method=RequestMethod.POST)
	public String searchPassword(Customer cust, HttpServletRequest request) throws SQLException, DuplicatedIdException{
		Customer customer=service.getCustomerById(cust.getCustId()); 
		try{	// SimpleMailMessage 
			SRN.sendEmail(customer); 
		}catch(Exception e){	// 입력이틀렸거나 이메일 전송실패 시에
			request.setAttribute("state", "error"); 
			return "/body/customer/searchPassword_form.jsp";
		}
		request.setAttribute("state", "success");
		return "/body/customer/searchPassword_form.jsp";
	}
//############################## 회원정보수정 ###############################################
	/*
	 * 					GET - 회원정보수정 페이지로 이동
	 * 					POST - modify.jsp 받아온 것으로 DB업데이트 
	 */
	@RequestMapping(value="login/modify.do", method=RequestMethod.GET)
	public String modifyForm(HttpSession session, ModelMap map){
		if(session.getAttribute("login_info")!=null){
			return "customer.modify_form";			
		}else if(session.getAttribute("login_info_manager")!=null){
			return "customer.modify_form";	
		}else{
			map.addAttribute("error_message", "로그인이 필요합니다");
			return "customer.login_form";
		}
	}
	
	@RequestMapping(value="login/modify.do", method=RequestMethod.POST)
	public String modify(Customer customer, HttpSession session, ModelMap map) throws SQLException{
		Customer loginInfo=(Customer)session.getAttribute("login_info");
		if(session.getAttribute("login_info")!=null){
			service.modifyCustomer(customer);
			customer.setJoinDate(loginInfo.getJoinDate());
			session.setAttribute("login_info", customer);
			insertBusinessRecord("회원", "회원정보수정", customer.getCustId());			//업무기록
			return "customer.customer_info"; 
		}else{
			map.addAttribute("error_message", "로그인이 필요합니다");
			return "customer.login_form";
		}
	}
	
	
//############################## Mypage 장바구니 #####################################	
	@RequestMapping("login/shoppingcart.do")
	public String shoppingCart(String custId, HttpSession session, ModelMap map) throws SQLException{
		if(session.getAttribute("login_info")!=null){
			System.out.println(dEMService.getDeliveryEnterpriseManagement());
			session.setAttribute("delivery", dEMService.getDeliveryEnterpriseManagement());
			List<OrderProduct> order=orderService.getOrderListById(custId);
			session.setAttribute("shop", order);
			return "customer.shoppingCart_form";
		}else{
			map.addAttribute("error_message", "로그인이 필요합니다");
			return "customer.login_form";
		}	
	}
//############################## 장바구니넣기 ###################################
	@RequestMapping("inShoppingCart.do")
	public String productInShoppingCart(OrderProduct orderPc, HttpSession session, HttpServletRequest request, ModelMap map) throws SQLException{
		if(session.getAttribute("login_info")!=null){
			orderService.joinOrderProduct(orderPc);		// 사용자가 변경한상품을 orderProduct에 넣는다.
			orderService.modifyOrderProductResult(orderPc.getCompleteId());
			List<OrderProduct> order=orderService.getOrderListById(orderPc.getCustId());
			session.setAttribute("shop", order);
			return "customer.shoppingCart_form";
		}else if(session.getAttribute("login_info_manager")!=null){
			return "customer.shoppingCart_form";
		}else{
			map.addAttribute("error_message", "로그인이 필요합니다");
			return "customer.login_form";
		}	
	}	
//######################### 주문내역  ###################################
	@RequestMapping("orderListMyPage.do")
	public String orderList(String custId, HttpSession session) throws SQLException{
		System.out.println(custId);
		List<OrderList> list=orderService.getOrderListByCustId(custId);
		session.setAttribute("MypageOrderList", list);
		System.out.println(list);
		return "customer.orderList";
	}
	
	@RequestMapping(value="orderList.do", method=RequestMethod.GET)
	public String orderList(String custId, HttpSession session, HttpServletRequest request) throws SQLException{
		System.out.println(custId);
		OrderProduct op = (OrderProduct)session.getAttribute("orderPc");
		OrderInfo oi = (OrderInfo)session.getAttribute("orderInfo");
		OrderList orderList=new OrderList(oi.getOrderNumber(), oi.getOrderName(), null, op.getCompleteName(), op.getCompletePrice(), custId);
		orderList.setOrderDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
		orderService.joinOrderList(orderList);
		
		//메인페이지 상품 순위 출력
		List<CompletePCResult> firstList= new ArrayList<CompletePCResult>();
		List<CompletePCResult> secondList= new ArrayList<CompletePCResult>();
		List<CompletePCResult> resultList= new ArrayList<CompletePCResult>();
		resultList = pmService.getCompletePCByPrice(10, 300000);//매개변수 1 : StartPrice, 2: EndPrice
		for(int idx=0; idx<2; idx++){
			firstList.add((CompletePCResult) resultList.get(idx));
		}resultList = pmService.getCompletePCByPrice(300001, 500000);//매개변수 1 : StartPrice, 2: EndPrice
		for(int idx=0; idx<2; idx++){
			firstList.add((CompletePCResult) resultList.get(idx));
		}request.setAttribute("firstList", firstList);
		resultList = pmService.getCompletePCByPrice(500001, 1000000000);//매개변수 1 : StartPrice, 2: EndPrice
		for(int idx=0; idx<2; idx++){
			secondList.add((CompletePCResult) resultList.get(idx));
		}resultList = pmService.getCompletePCByCPUBrand("cpu", "intel");
		for(int idx=0; idx<1; idx++){
			secondList.add((CompletePCResult) resultList.get(idx));
		}resultList = pmService.getCompletePCByCPUBrand("cpu", "amd");
		for(int idx=0; idx<1; idx++){
			secondList.add((CompletePCResult) resultList.get(idx));
		}request.setAttribute("secondList", secondList);

		return "customer.main";
	}

//###################### 회원전체정보조회 ###########################
	@RequestMapping("customerListPaging.do")
	public String customerListPaging(HttpServletRequest request, HttpSession session) throws SQLException{
		System.out.println("전체회원관리");
		request.setAttribute("menu_category", "customer");
		List<Customer> list = (List<Customer>)service.getCustomerList();
		request.setAttribute("list", list);
		session.setAttribute("result", list);					//Customer 엑셀 파일 전송
		return "admin.customer/customerListPaging";
	}	
//###################### 회원탈퇴정보조회 ###########################	
	@RequestMapping("customerRemoveList.do")
	public String customerRemoveList(HttpServletRequest request, HttpSession session) throws SQLException{
		System.out.println("탈퇴관리");
		request.setAttribute("menu_category", "customer");
		List<CustomerOut> list=(List<CustomerOut>)service.getCustomerOutList();
		request.setAttribute("list", list);
		session.setAttribute("result", list);					//Customer 엑셀 파일 전송
		return "admin.customer/customerRemoveList";
	}
	@RequestMapping("customerRestore.do")
	public String customerRestore(String custId, HttpServletRequest request) throws SQLException{
		System.out.println(custId);
		request.setAttribute("menu_category", "customer");
		service.deleteCustomerOutById(custId);
		return "admin.customer/customerRemoveList";
	}
	@RequestMapping("customerDelete.do")
	public String customerDelete(String custId, HttpServletRequest request) throws SQLException{
		request.setAttribute("menu_category", "customer");
		service.deleteCustomerOutById(custId);// customerOut
		service.removeCustomerById(custId);// customer 
		return "admin.customer/customerRemoveList";
	}
//###################### 회원탈퇴 #############################
	@RequestMapping(value="login/removeCustomer.do", method=RequestMethod.POST)
	public String removeCustomer(HttpSession session, String custId, String name, String email, String outReason) throws Exception{
		CustomerOut custOut=new CustomerOut();
		custOut.setCustId(custId); custOut.setName(name);
		custOut.setEmail(email); custOut.setOutReason(outReason);
		service.insertRemoveCustomer(custOut); //탈퇴회원테이블로 넣어줌
		session.invalidate();  //로그아웃
		return "customer.main";
	}	
//###################### (관리자) 이름, 생년월일, 핸드폰, 주소, 가입일 ###########################
	@RequestMapping("searchCustomer.do")
	public String searchCustomer(String search_type, String input, HttpServletRequest request, HttpSession session) throws SQLException{
		List<Customer> list=null;
		request.setAttribute("menu_category", "customer");
		if(search_type.equals("all")){	
			list=service.getCustomerList();
		}else if(search_type.equals("name")){
			list=service.getCustomerListByName(input);
		}else if(search_type.equals("birth")){
			list=service.getCustomerListByBirth(input);
		}else if(search_type.equals("phone")){
			list=service.getCustomerListByPhone(input);
		}else if(search_type.equals("address")){
			list=service.getCustomerListByAddress(input);
		}else if(search_type.equals("joinDate")){
			list=service.getCustomerListByJoinDate(input);
		}
		request.setAttribute("list",list);
		session.setAttribute("result", list);
		return "admin.customer/customerListPaging";
		
	}
//###################### excel 파일 생성 ###########################
	@RequestMapping("customerView.do")
	public String customerView(Map<String, Object> model, HttpSession session) throws SQLException{
		List<Customer> list = (List<Customer>)session.getAttribute("result");
		model.put("customer", list);
		return "customerView";
	}
	
	@RequestMapping("mileagePage.do")
	public ModelAndView customerMileageView(){
		return new ModelAndView("customer.mileagePage");
	}
//###################### BusinessRecord DB저장 메소드 ###########################
	private void insertBusinessRecord(String sort, String sort2, String disposer) throws SQLException {
		bRService.joinBusinessRecord(new BusinessRecord(null, sort, sort2, new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()), disposer));
	}

}

